﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using Microsoft.Practices.ServiceLocation;
using UIExample.ViewModel;

namespace UIExample.Behavior
{
    public class FrameworkElementDropBehavior : Behavior<FrameworkElement>
    {
        private Type dataType = typeof(WK35705XML.UMP); //the type of the data that can be dropped into this control


        protected override void OnAttached()
        {
            base.OnAttached();
           
            this.AssociatedObject.AllowDrop = true;
            this.AssociatedObject.DragEnter += new DragEventHandler(AssociatedObject_DragEnter);
            this.AssociatedObject.DragOver += new DragEventHandler(AssociatedObject_DragOver);
            this.AssociatedObject.DragLeave += new DragEventHandler(AssociatedObject_DragLeave);
            this.AssociatedObject.Drop += new DragEventHandler(AssociatedObject_Drop);
        }

        void AssociatedObject_Drop(object sender, DragEventArgs e)
        {
      
            //if the data type can be dropped 
            if (e.Data.GetDataPresent(dataType) && e.Data.GetData(dataType) is WK35705XML.UMP)
            {
                //drop the data
                if (e.Source is Grid)
                {
                    ServiceLocator.Current.GetInstance<MainViewModel>()
                        .Drop(e.Data.GetData(dataType) as WK35705XML.UMP, e.Source as Grid, e.GetPosition(e.Source as Grid));
                }
            }
            e.Handled = true;
            return;
        }

        void AssociatedObject_DragLeave(object sender, DragEventArgs e)
        {

            e.Handled = true;
        }

        void AssociatedObject_DragOver(object sender, DragEventArgs e)
        {

            //if item can be dropped
            if (e.Data.GetDataPresent(dataType))
            {
                //give mouse effect
                this.SetDragDropEffects(e);
                    
            }
         
            e.Handled = true;
        }

        void AssociatedObject_DragEnter(object sender, DragEventArgs e)
        {

            
            

         
            //e.Handled = true;
        }

        /// <summary>
        /// Provides feedback on if the data can be dropped
        /// </summary>
        /// <param name="e"></param>
        private void SetDragDropEffects(DragEventArgs e)
        {
            e.Effects = DragDropEffects.None;  //default to None

            //if the data type can be dropped 
            if (e.Data.GetDataPresent(dataType))
            {
                e.Effects = DragDropEffects.Copy;
            }
        }

    }

}
